<%@page  import="java.text.*,java.util.*,merlin.beans.*,merlin.dao.*,merlin.managers.*,merlin.servlets.*,merlin.utils.*" %>
<!--

	Purpose	:	Free Updates Main Page.
	Author	:	Sandip Bhattacharya (sandipkb@yahoo.com)

-->

<%!
	// User types
	static final Integer USER_TYPE_MERLIN_RESEARCHER = new Integer(1);
	static final Integer USER_TYPE_FREE_UPDATES = new Integer(2);

	// Determines whether the Custom Reports tab is visible or not for this user.
	// Custom Reports is available only for user who have subscribed for Database version.
	boolean showCustomReportsTab = false;

%>


<%
	// sanity check
	if(session.getAttribute("username") == null){
		response.sendRedirect("mr_loginFreeUpdates.jsp");
		return;
	}

	ApplicationResources resource = ApplicationResources.getInstance();

	String separatorString = resource.getProperty("separatorString");
	String separatorPattern = resource.getProperty("separatorPattern");

	CustomerDetailsBean bean = (CustomerDetailsBean)session.getAttribute("userDetails");
	int customerDetailsId = bean.getCustomerDetailsId();

	showCustomReportsTab = (bean.getReportType() == 3);

	int reportId = Integer.parseInt((String)session.getAttribute("reportId"));
	String username = (String)session.getAttribute("username");
%>

<html>
	<head>
	
		<script>
			var jsShowCustomReportsTab = <%= showCustomReportsTab %>;
		</script>
	
		<meta HTTP-EQUIV="Cache-Control"  CONTENT="no-cache" />
		<meta HTTP-EQUIV="Expires"        CONTENT="1 Jan 1980" />
		<meta HTTP-EQUIV="MaxAge"         CONTENT="0" />
		<meta HTTP-EQUIV="Pragma-Control" CONTENT="no-cache" />

		<!-- begin imports for creation of the tabs -->
		<link rel="stylesheet" type="text/css" href="mr_tabs/tabcontent.css" />
		<script type="text/javascript" src="mr_tabs/tabcontent.js">
		</script>
		<!-- ends imports for creation of the tabs -->

		<!-- begin imports for Settings Menu -->
		<link rel="stylesheet" type="text/css" href="mr_menus/themes/office_xp/office_xp.css" />
		<script type="text/javascript" src="mr_menus/jsdomenubar.js"></script>
		<script type="text/javascript" src="mr_menus/jsdomenu.js"></script>
		<script type="text/javascript" src="mr_menus/jsdomenu.inc.freeupdatesExtended.js"></script>
		<!-- ends imports for Settings Menu -->

		<!-- begin DWR imports -->
		<script type='text/javascript' src='dwr/interface/MsalResearchersManager.js'></script>
		<script type='text/javascript' src='dwr/engine.js'></script>
		<script type='text/javascript' src='dwr/util.js'></script>
		<!-- ends DWR imports -->

		<!-- begin Prototype import -->
		<script type='text/javascript' src='mr_scripts/prototype.js'></script>
		<!-- ends Prototype import -->

		<!-- begins JST imports -->
		<script type="text/javascript" src="mr_scripts/template.js"></script>
		<!-- ends JST imports -->

		<!-- begin jQuery import -->
		<script type='text/javascript' src='mr_scripts/jquery.js'></script>
		<!-- ends jQuery import -->
		
		<!-- begin imports for sorting of the table -->
        <script type="text/javascript" src="mr_scripts/sorttable.js"></script>
        <style>
			.sortablecolumn {
				cursor: pointer;
				cursor: hand;
			}
        </style>
		<!-- ends imports for sorting of the table -->

		<script>

			jQuery.noConflict();
		
			// for DWR calls for saving the companies selected.
			var reportId = <%= reportId%>;
			var username = '<%=username%>';

			// Used to determine if a logout comand has been sent or not. It is set to "true"
			// when the user clicks on the "send List" button, or when he clicks the "Logout" link.
			// This variable is used by the logOutOnUnload() function, which gets executed on the unloading of this page.
			// The logOutOnUnload() function invokes an asynchronous call on the server with the
			// mode=logout request parameter. This flag prevents a spurious call , when a mail
			// is being generated, which also results in the unloading of this page but also
			// results in a session invalidation activity on the server end.
			// The logOutOnUnload() function is primarily designed to be executed in case the user simply
			// closes the browser window without properly logging out.
			var logoutCommandSent = false;

			var doLogout = true;

			function newXMLHttpRequest() {

				var xmlreq = false;

				if (window.XMLHttpRequest) {
					// Create XMLHttpRequest object in non-Microsoft browsers
	    			xmlreq = new XMLHttpRequest();
				} else if (window.ActiveXObject) {
					// Create XMLHttpRequest via MS ActiveX
					try {
						// Try to create XMLHttpRequest in later versions
						// of Internet Explorer
						xmlreq = new ActiveXObject("Msxml2.XMLHTTP");
					} catch (e1) {
						// Failed to create required ActiveXObject
						try {
							// Try version supported by older versions
							// of Internet Explorer
							xmlreq = new ActiveXObject("Microsoft.XMLHTTP");
						} catch (e2) {
							// Unable to create an XMLHttpRequest with ActiveX
						}
					}
				}
				return xmlreq;
			}

			// function to force a log-out activity when the window is getting unloaded.
			// this is a backup function in case the user has not logged out cleanly.
			function logOutOnUnload(){

				if(!doLogout) return;

				if(!logoutCommandSent){
					// Obtain an XMLHttpRequest instance
					var req = newXMLHttpRequest();

					// Set the handler function to receive callback notifications
					// from the request object
					//var handlerFunction = getReadyStateHandler(req, updatePage);
					//req.onreadystatechange = handlerFunction;

					// Open an HTTP POST connection to the shopping cart servlet.
					// Third parameter specifies request is asynchronous.
					req.open("POST", "merlin", true);

					// Specify that the body of the request contains form data
					req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

					// Send form encoded data stating that I want to add the
					// specified item to the cart.
					req.send("mode=logout");
				}
			}

			// function which gets called when the usre clicks the "log out" link.
			function logOut(frm){
				logoutCommandSent = true;
				document.frmSearch.mode.value	= "logout";
				document.frmSearch.action		= "merlin";
				document.frmSearch.target		= "_top";
				document.frmSearch.submit();
			}

			////////////// Utility Functions ////////////////////

			function disableEnable(bFlag){
				document.frmSearch.txtSearch.disabled = bFlag;
				document.frmSearch.btnSearch.disabled = bFlag;
				document.frmSearch.lstCompanies.disabled = bFlag;
				document.frmSearch.btnAddCompany.disabled = bFlag;
				document.frmSearch.btnRemoveCompany.disabled = bFlag;
				document.frmSearch.btnUpdate.disabled = bFlag;
				document.frmSearch.lstSelectedCompanies.disabled = bFlag;
				document.frmSearch.lstDirectors.disabled = bFlag;
				document.frmSearch.btnPrintPDF.disabled = bFlag;

				$("btnRefresh").disabled = bFlag;

				document.frmDeleteCompaniesTab.btnLoadCompanies.disabled = bFlag;
				document.frmDeleteCompaniesTab.btnAddCompany.disabled = bFlag;
				document.frmDeleteCompaniesTab.btnRemoveCompany.disabled = bFlag;
				document.frmDeleteCompaniesTab.btnUpdate.disabled = bFlag;
			}

			function isBlank(str){
				var len = str.length;
				if(len==0)return true;	// zero-length string
				for(i=0;i<len;i++){
					if(str.charAt(i) !=' ' && str.charAt(i) !='\n')return false; //some character is there
				}
				return true;
			}

			/**
			* 	Utility function to add an option into the list, and optionally sorting it.
			*/
			function addToList(lstToAdd,aOption,toSort){
				// browser specific addition, different in Mac Safari.
				var isSafari = navigator.userAgent.indexOf("Safari") > -1;
				if(isSafari){
					// Mac Safari
					lstToAdd.add(aOption);
				}else{
					// other browsers.
					lstToAdd.options.add(aOption);
				}
				// sort the data.
				if(toSort)sortSelect(lstToAdd);
			}

			function getSelectedCompanies(list){

				var lstLen = list.length;
				if(lstLen == 0 )return "";

				var reportTitles ="";
				for(i=0;i < lstLen - 1;i++){
					reportTitles += list.options[i].value + "<%=separatorString %>" + list.options[i].text + "<%=separatorString %>";
				}
				reportTitles += list.options[lstLen-1].value + "<%=separatorString %>" + list.options[lstLen-1].text

				return reportTitles;
			}
			////////////// Ends Utility Functions //////////////////

			/////////////////Message Display Functions ///////////
			function displayMessage(message){
				message = "<SPAN style='color:GREEN; font: 12px arial, verdana, sans-serif ;font-weight:bold;'>" + message + "</SPAN>"
				var divMessage ;
				if(document.all){
					// IE 4+
					divMessage 	= document.all("divMessage");
				}else if(document.getElementById){
					// Mozilla/NS 6+/Firefox
					divMessage 	= document.getElementById("divMessage");
				}else if(document.layers){
					divMessage 	= document.layers["divMessage"];
				}
				divMessage.innerHTML = message;
			}

			function displayError(errMessage){
				errMessage = "<SPAN style='color:red; font: 12px arial, verdana, sans-serif ;font-weight:bold;'>" + errMessage + "</SPAN>"
				var divMessage ;
				if(document.all){
					// IE 4+
					divMessage 	= document.all("divMessage");
				}else if(document.getElementById){
					// Mozilla/NS 6+/Firefox
					divMessage 	= document.getElementById("divMessage");
				}else if(document.layers){
					divMessage 	= document.layers["divMessage"];
				}
				divMessage.innerHTML = errMessage;
			}

			function clearMessage(){
				var emptyMessage = "<SPAN style='font: 12px arial, verdana, sans-serif ;font-weight:bold;'>&nbsp;</SPAN>"
				var divMessage ;
				if(document.all){
					// IE 4+
					divMessage 	= document.all("divMessage");
				}else if(document.getElementById){
					// Mozilla/NS 6+/Firefox
					divMessage 	= document.getElementById("divMessage");
				}else if(document.layers){
					divMessage 	= document.layers["divMessage"];
				}
				divMessage.innerHTML = emptyMessage;
			}

			function displayNumSelectedCompanies(lst){
				var txtSingle   = " Company to include in your new report<br>(click to delete a company)";
				var txtMultiple = " Companies to include in your new report<br>(click to delete a company)";
				var spnMessage ;
				if(document.all){
					// IE 4+
					spnMessage 	= document.all("spnSelectedCompanies");
				}else if(document.getElementById){
					// Mozilla/NS 6+/Firefox
					spnMessage 	= document.getElementById("spnSelectedCompanies");
				}else if(document.layers){
					spnMessage 	= document.layers["spnSelectedCompanies"];
				}
				if(lst.length == 1){
					spnMessage.innerHTML = lst.length + txtSingle ;
				}else{
					spnMessage.innerHTML = lst.length + txtMultiple;
				}
			}

			function cleanAllEntries(){
				var frm = document.frmSearch;

				var divAddress , divShareholders ,divBusinessDescription,divSummaryFinancial;

				if(document.all){
					// IE 4+
					divAddress 				= document.all("divAddress");
					divShareholders 		= document.all("divShareholders");
					divBusinessDescription 	= document.all("divBusinessDescription");
					divSummaryFinancial 	= document.all("divSummaryFinancial");
					divSubsidiary			= document.all("divSubsidiary");
				}else if(document.getElementById){
					// Mozilla/NS 6+/Firefox
					divAddress 				= document.getElementById("divAddress");
					divShareholders 		= document.getElementById("divShareholders");
					divBusinessDescription 	= document.getElementById("divBusinessDescription");
					divSummaryFinancial		= document.getElementById("divSummaryFinancial");
					divSubsidiary			= document.getElementById("divSubsidiary");
				}else if(document.layers){
					divAddress 				= document.layers["divAddress"];
					divShareholders 		= document.layers["divShareholders"];
					divBusinessDescription 	= document.layers["divBusinessDescription"];
					divSummaryFinancial		= document.layers["divSummaryFinancial"];
					divSubsidiary			= document.getElementById("divSubsidiary");
				}
				divAddress.innerHTML 				= "";
				divShareholders.innerHTML   		= "";
				divBusinessDescription.innerHTML 	= "";
	            divSummaryFinancial.innerHTML		= "";
	            divSubsidiary.innerHTML				= "";


				var lstCompanies = frm.lstCompanies;
				// Remove all the previous entries in the lstCompanies select box
				for(i=lstCompanies.length-1;i>=0;i--){
					lstCompanies.remove(i);
				}

				var lstDirectors = frm.lstDirectors;
				// Remove all the previous entries
				for(i=lstDirectors.length-1;i>=0;i--){
					lstDirectors.remove(i);
				}
			}

			//////////////Ends Message Display Functions /////////

			//////////////Search Functions //////////////////////
			function searchCompanyByKeyword(strSearch,frm){
				if(isBlank(strSearch)){
					alert("Cannot leave the search field blank");
					return false;
				}
				if(strSearch.length < 3){
					alert("Enter at least 3 characters in the search field");
					return false;
				}

				if(isSessionValid()){
					// disable the various UI components so that the user cannot generate
					// another request as long as the search is going on.
					disableEnable(true);

					//parent.frameMessage.displayMessage("Searching...");
					displayMessage("Searching.....");
	   				parent.frameSearch.document.frmSearch.mode.value="searchCompanyByKeyword";
	   				parent.frameSearch.document.frmSearch.hidSearch.value=strSearch;
	   				parent.frameSearch.document.frmSearch.hidCompanies.value = getSelectedCompanies(frm.lstSelectedCompanies);
	   				parent.frameSearch.document.frmSearch.hidSearchType.value = getSearchType(frm);
	   				parent.frameSearch.document.frmSearch.submit();
	   				return true;
				}
			}

			/**
			* 	Determine whether the search for companies (search word entered in the search box),
			*	is alpha-key based or keywrd based.
			*/
			function getSearchType(frm){
				if(frm.radSearchType[0].checked){
					return frm.radSearchType[0].value;
				}else{
					return frm.radSearchType[1].value;
				}
			}

			function searchCompanyByCompanyNumber(strNumber,frm){
				if(strNumber == null || strNumber == "" || strNumber == "-1"){
					return;
				}

				if(isSessionValid()){
					// disable the various UI components so that the user cannot generate
					// another request as long as the search is going on.
					disableEnable(true);

					//parent.frameMessage.displayMessage("Searching...");
					displayMessage("Searching.....");
	   				parent.frameSearch.document.frmSearch.mode.value="searchCompanyByCompanyNumber";
	   				parent.frameSearch.document.frmSearch.hidSearch.value=strNumber;
	   				parent.frameSearch.document.frmSearch.hidCompanies.value = getSelectedCompanies(frm.lstSelectedCompanies);
	   				parent.frameSearch.document.frmSearch.submit();
				}
			}

			function searchCompanyByDirector(strNumber,frm){
				if(strNumber == null || strNumber == "" || strNumber == "-1"){
					return;
				}

				if(isSessionValid()){
					// disable the various UI components so that the user cannot generate
					// another request as long as the search is going on.
					disableEnable(true);

					//parent.frameMessage.displayMessage("Searching...");
					displayMessage("Searching.....");
					parent.frameSearch.document.frmSearch.mode.value="searchCompanyByDirector";
	   				parent.frameSearch.document.frmSearch.hidSearch.value=strNumber;
	   				parent.frameSearch.document.frmSearch.hidCompanies.value = getSelectedCompanies(frm.lstSelectedCompanies);
	   				parent.frameSearch.document.frmSearch.submit();
				}
			}
			//////////////Ends Search Functions /////////////////////////

			/**
			* 	Function called from the "Add" button in Tab 2. The function checks against
			*	duplicacy in the Tab 3 'added' list, and if the company is not present, adds
			*	the company details into Tab 2 'add' list and Tab 3 'add' list. The Tab 3 entry
			*	is colored in green to signify that this is a new company not currently present
			*	in the report.
			*/
			function addCompany(){

				var lstTab2From = document.frmSearch.lstCompanies;
				var lstTab2To	= document.frmSearch.lstSelectedCompanies;
				var lstTab3To	=  document.frmDeleteCompaniesTab.selAddCompanyList;

				try{
					var index = lstTab2From.selectedIndex;
					if(index == -1){
						alert("Select a company to add");
						return;
					}
					// check if the company already exists in the selected companies list.
					var exists = false;
					var valCompany = lstTab2From.options[index].value;
					var lstToLen = lstTab3To.options.length;
					for(var j=0;j<lstToLen;j++){
						if(valCompany == lstTab3To.options[j].value){
							alert("Company already selected in the report");
        					exists = true;
	        				lstTab2From.options[index].selected = false;
							break;
	    		    	}
    	    		}
			        if(! exists){
						// add the company to the tab 2 list
	    			    var aOption = document.createElement("OPTION");
						aOption.text = lstTab2From.options[index].text;
						aOption.value = lstTab2From.options[index].value;

						addToList(lstTab2To,aOption,true);

						// add it tab 3 list, after setting the color to green.
						aOption.style.color = 'green';
						addToList(lstTab3To,aOption,true);

						// and remove it from the other
						lstTab2From.remove(index);

						displayNumSelectedCompanies(lstTab2To);
						displayCountOfCompaniesTab3();
						sendCompanyListForStorage();
					}
				}catch(e){
					alert("addCompany : " + e.message);
				}
			}

			function sendReportData(frm){
				if(isSessionValid()){
					displayMessage("Sending Mail...");
	    			logoutCommandSent = true;
	    			frm.mode.value="sendMailToAddRemoveCompanies";
	    			frm.hidCompanies.value= getSelectedCompanies(frm.lstSelectedCompanies);
	    			frm.hidCompaniesToRemove.value= getSelectedCompanies(document.frmDeleteCompaniesTab.selDelCompanyList);
	    			frm.submit();
				}
			}

			/**
			* 	Function called from Tab 2 "Delete Company" button.
			*	The company gets removed from both the Tab 2 and Tab 3 added list.
			*/
			function deleteCompany(lst){
				var isAnySelected = false;
				var companyNumber;

				for(i = lst.length -1;i>=0;i--){
					if(lst.options[i].selected == true){
						companyNumber = lst.options[i].value;
						lst.options[i] = null;
						isAnySelected = true;
					}
				}
				if(!isAnySelected){
					alert("Select a company to delete");
				}else{
					// remove from the Tab 3 list also.
					var opts = document.frmDeleteCompaniesTab.selAddCompanyList.options;
					for(var x=0;x<opts.length;x++){
						if(opts[x].value == companyNumber){
							opts[x] = null;
							break;
						}
					}
					displayNumSelectedCompanies(lst);
					displayCountOfCompaniesTab3();
					sendCompanyListForStorage();
				}
			}

        	// sort function - ascending (case-insensitive)
	        function sortFuncAsc(record1, record2) {
    	        var value1 = record1.optText.toLowerCase();
        	    var value2 = record2.optText.toLowerCase();
            	if (value1 > value2) return(1);
	            if (value1 < value2) return(-1);
    	        return(0);
        	}

		    // sort the select object in ascending order.
			function sortSelect(selectToSort) {
				try{
					// copy options into an array
				    var myOptions = new Array();
					for (var loop=0; loop<selectToSort.options.length; loop++) {
						myOptions[loop] = { optText:selectToSort.options[loop].text, optValue:selectToSort.options[loop].value, optColor:selectToSort.options[loop].style.color };
					}

					// sort array
					myOptions.sort(sortFuncAsc);

					// copy sorted options from array back to select box
					selectToSort.options.length = 0;

					// browser identification
					var isSafari =	(navigator.userAgent.indexOf("Safari") > -1)? true: false;

					for (var loop=0; loop<myOptions.length; loop++) {
						var optObj = document.createElement('option');
						optObj.text = myOptions[loop].optText;
						optObj.value = myOptions[loop].optValue;
						optObj.style.color = myOptions[loop].optColor;
						if(isSafari){
							selectToSort.add(optObj);
						}else{
							selectToSort.options.add(optObj);
						}
					}
				}catch(e){
					alert("sortSelect : " + e.message);
				}
			}

			function generatePDF(companyId){
				if(companyId == null || companyId==""){
					alert("Please select a company from the search results list");
				}else{
					if(isSessionValid()){
						// open on a new window
						window.open("merlin?mode=createPDF&companyId=" + companyId,"pdf","height=600,width=600,resizable=yes,menubar=yes,scrollbars=yes,toolbar=no");
					}
   				}
			}

	    	function downloadReport(reportid,row, reportFormat){
	    		// once the report gets clicked, it is not available again for that session.
	    		row.style.color = '#ff0000';
	    		row.style.cursor='default';
	    		row.onclick="";
	    		row.cells[3].innerHTML='Downloading...';
	    		document.location = "merlin?mode=pdfReportDownloadFreeUpdates&downloadId=" + reportid + "&reportFormat=" + reportFormat;
	    	}

			// refreshes the page after every 10 mins.
	    	function reloadPage(){
				if(isSessionValid()){
					doLogout=false;
					document.location='mr_main.jsp';
				}
	    	}


	    	function sendCompanyListForStorage(){
				if(isSessionValid()){
		    		var companies = getSelectedCompanies(document.frmSearch.lstSelectedCompanies);
		    		MsalResearchersManager.storeSelectedCompanies(username,companies,reportId,null);
		    	}
	    	}

			////////////////////////////// Tab 3 Functions ///////////////////////

			/**
			* 	Function that makes a DWR call to load the companies list for Tab 3.
			*/
	    	function loadCompaniesInReport(){
				if(isSessionValid()){
    	        	var disabledZone = $('disabledZone');
	            	if(disabledZone != null)disabledZone.style.display='';
	            	disableEnable(true);
		    		DWRUtil.useLoadingMessage("Loading companies list...");
		    		MsalResearchersManager.getCompaniesInReport(reportId,handleLoadCompaniesInReport);
		    	}
	    	}

	    	function handleLoadCompaniesInReport(data){

				// a hack to disable the DWR error message permanently, otherwise it starts flashing
				// for every DWR call (a bug ?).
            	var disabledZone = $('disabledZone');
            	disabledZone.style.display='none';

            	disableEnable(false);

	    		var lstTo = document.frmDeleteCompaniesTab.selAddCompanyList;

				for(var i=0;i<data.length;i++){
					// add the company to the list
    			    var aOption = document.createElement("OPTION");
					aOption.text = data[i].companyName;
					aOption.value = data[i].registeredNumber;
					addToList(lstTo,aOption,false);
	    		}
	    		// add the reports that are already present in the Tab 2 'Add companies' list.
	    		// If a company already exists in the list of Tab 3, then ignore it, else add
	    		// it with green color.
	    		var optsFrom = document.frmSearch.lstSelectedCompanies.options;
				for(var x = 0; x < optsFrom.length; x++){
					var exists = false;
					var valCompany = optsFrom[x].value;
					var lstTolen = lstTo.length;
					for(var j=0;j<lstTolen;j++){
						if(valCompany == lstTo.options[j].value){
        					exists = true;
							break;
	    		    	}
    	    		}
			        if(! exists){
						// add the company to the list
	    			    var aOption = document.createElement("OPTION");
						aOption.text = optsFrom[x].text;
						aOption.value = optsFrom[x].value;
                        aOption.style.color = 'green';

						addToList(lstTo,aOption,false);
       				}
       			}
       			displayCountOfCompaniesTab3();
				// sort the data.
				sortSelect(lstTo);
	    	}

	    	/**
	    	* 	Function invoked on clicking the 'Add Company' button in tab 3.
	    	*/
	    	function addCompanyTab3(){
	    		var lstFrom = document.frmDeleteCompaniesTab.selDelCompanyList;
	    		var lstTo = document.frmDeleteCompaniesTab.selAddCompanyList;

				var index = lstFrom.selectedIndex;
				if(index == -1){
					alert("Select a company to add");
					return;
				}

				// handle multiple selections
				for(var x = lstFrom.options.length - 1; x >=0;x--){
					if(lstFrom.options[x].selected){
						// add the company to the tab 2 list
					    var aOption = document.createElement("OPTION");
						aOption.text = lstFrom.options[x].text;
						aOption.value = lstFrom.options[x].value;
						addToList(lstTo,aOption,false);
						// and remove it from the other
						lstFrom.remove(x);
					}
				}
				displayCountOfCompaniesTab3();
                sortSelect(lstTo);


	    	}

	    	/**
	    	* 	Function called on clicking the 'Remove Company' button in Tab 3.
	    	*/
			function removeCompanyTab3(){
	    		var lstFrom = document.frmDeleteCompaniesTab.selAddCompanyList;
	    		var lstTo = document.frmDeleteCompaniesTab.selDelCompanyList;

				var index = lstFrom.selectedIndex;
				if(index == -1){
					alert("Select a company to remove");
					return;
				}

				// handle multiple selections
				for(var x = lstFrom.options.length - 1; x >=0;x--){
					if(lstFrom.options[x].selected){
						// If this record is not of green color (newly added), then move it to the
						// 'del' list, else remove it from both Tab 2 and 3 'added' lists.
		    			if(lstFrom.options[x].style.color != 'green'){
		    				// move it to the 'del' list.
						    var aOption = document.createElement("OPTION");
							aOption.text = lstFrom.options[x].text;
							aOption.value = lstFrom.options[x].value;

							addToList(lstTo,aOption,false);
		                    lstFrom.remove(x);

		    			}else{

		    				var companyNumber = lstFrom.options[x].value;
		    				lstFrom.remove(x);
							// remove from the Tab 2 list also.
							var opts = document.frmSearch.lstSelectedCompanies.options;
							for(var z=0;z<opts.length;z++){
								if(opts[z].value == companyNumber){
									opts[z] = null;
									break;
								}
							}
		    			}
					}
				}
				displayNumSelectedCompanies(document.frmSearch.lstSelectedCompanies);
				sendCompanyListForStorage();
				displayCountOfCompaniesTab3();
                sortSelect(lstTo);
	    	}

			function displayCountOfCompaniesTab3(){
				var txtSingle   = " Company now listed in the report";
				var txtMultiple = " Companies now listed in the report";
				var spnMessage = $("divAddedCompanies");

				var count = document.frmDeleteCompaniesTab.selAddCompanyList.options.length;

				if(count == 1){
					spnMessage.innerHTML = count + txtSingle ;
				}else{
					spnMessage.innerHTML = count + txtMultiple;
				}
			}

		</script>

		<script>
			// the session invalidation duration, in milliseconds
			var lastAccessedTime = new Date().getTime();

			// the session invalidation duration, in milliseconds
			var sessionDuration = <%= session.getMaxInactiveInterval()%> * 1000;

			var timerPointer = -1;
			var timerWarning = -1;

			/**
			* 	Function to check if the user is still having a valid session or has timed out.
			*	Adds two timeout functions to the windowd object -
			*		1. a function that shows a warning message to the user that his session is about to expire
			*			with an option to stay connected
			*		2. a automatic logout if the session times out.
			*/
			function isSessionValid(){
				var currentTime  = new Date().getTime();

				if((currentTime - lastAccessedTime) < sessionDuration){
					// session is valid.
					lastAccessedTime = currentTime;

					// cancel the existing timer(if any),and start again.
					if(timerPointer != - 1)clearTimeout(timerPointer);
					if(timerWarning != - 1)clearTimeout(timerWarning);

					timerPointer = setTimeout('logOut(document.frm)',sessionDuration);
					timerWarning = setTimeout('showLogoutWarning()',sessionDuration - 10000);

					return true;
				}else{
					// session has timed out, send to logout procedure.
					logOut(document.frm);
					return false;
				}
			}

			/**
			*  Shows the logout warning DIV.
			*/
			function showLogoutWarning(){
				document.getElementById("divStayLoggedIn").style.visibility = "visible";
			}

			/**
			* 	A function that provides the user the option to stay logged on 10 secs before the logout event.
			*/
			function stayLoggedOn(){
				if(isSessionValid()){
					document.getElementById("divStayLoggedIn").style.visibility = "hidden";
					MsalResearchersManager.stayConnected();
				}
			}

			/**
			* 	Function to handle a change in the reports list combo box in tab 1.
			*/
			function reportChanged(list){
				MsalResearchersManager.setNewReportId(list.options[list.selectedIndex].value,list.options[list.selectedIndex].text,handleReportIdChanged);
			}

			function handleReportIdChanged(data){
				if(data != -1){
					reportId = data;

					// sync the two comboboxes.
					var lst  = $("selReportsTab2");
					if(lst != null){
						for(var i=0;i<lst.length;i++){
							if(lst.options[i].value == reportId){
								lst.selectedIndex = i;
								break;
							}
						}
					}

					lst  = $("selReportsTab3");
					if(lst != null){
						for(var i=0;i<lst.length;i++){
							if(lst.options[i].value == reportId){
								lst.selectedIndex = i;
								break;
							}
						}
					}

					// clean tab 3 listboxes.
					lst = document.frmDeleteCompaniesTab.selAddCompanyList;
					for(i = lst.length -1;i>=0;i--){
						lst.options[i] = null;
					}
					lst = document.frmDeleteCompaniesTab.selDelCompanyList;
					for(i = lst.length -1;i>=0;i--){
						lst.options[i] = null;
					}
					displayCountOfCompaniesTab3();

					// remove the data for the tab 2 'Companies to include" list and fetch it again from the server.
					lst = document.frmSearch.lstSelectedCompanies;
					for(i = lst.length -1;i>=0;i--){
						lst.options[i] = null;
					}

					MsalResearchersManager.getSelectedCompanies(username,reportId,handleSelectedCompaniesForTab2List);
				}
			}

			function handleSelectedCompaniesForTab2List(data){
				if(data != null){
					var lst = document.frmSearch.lstSelectedCompanies;
					for(i=0;i<data.length;i++){
	    			    var aOption = document.createElement("OPTION");
						aOption.text = data[i][1];
						aOption.value = data[i][0];
						addToList(lst,aOption,false);
					}
				}
			}
		</script>


		<!-- Script for the 'Customize Reports' facility -->
		<%
			if(showCustomReportsTab){
		%>
		<script>

			var companiesFinancialData = new Array();
			var companyChanged = true;	// marker to hold info whether the company was changed in the combo box.
			var selectedCompanies = new Array();	// companies present in list 2.

			var customerDetailsId = <%=customerDetailsId%>

			String.prototype.trim = function () {
			    return this.replace(/^\s*/, "").replace(/\s*$/, "");
			}


			function fetchCompanyFinancialDetails(frm, eventSource){
				if(frm.selReportsTab4.selectedIndex == 0 || frm.selFinancialCriteria.selectedIndex == 0)return;
				if(isSessionValid()){
					var companyIds;
					if(companyChanged){
						companyChanged = false;
						companyIds = null;
					}else{
						companyIds = "";
						if(document.frmCustomiseReportTab.chkFinancials){
							for(var i=0;i<document.frmCustomiseReportTab.chkFinancials.length;i++){
								companyIds += ",'" + document.frmCustomiseReportTab.chkFinancials[i].value + "'";
							}
							if(companyIds.length > 0){
								companyIds = companyIds.substr(1);
							}
						}
					}

					var reportId = frm.selReportsTab4.options[frm.selReportsTab4.selectedIndex].value;
					var finCriteriaId = frm.selFinancialCriteria.options[frm.selFinancialCriteria.selectedIndex].value;

					var minValue = "";
					var maxValue = "";

					if(eventSource == "button"){
						// take the min and max.
						minValue = frm.txtMinValue.value;
						maxValue = frm.txtMaxValue.value;
						if(minValue == "" && maxValue == ""){
							alert("enter at least one of either min or max range");
							return;
						}
					}

    	        	var disabledZone = $('disabledZone');
	            	if(disabledZone != null)disabledZone.style.display='';
		    		DWRUtil.useLoadingMessage("Loading companies list...");
					MsalResearchersManager.getFinancialDetailsForCompaniesByReportAndFinancialType(reportId,finCriteriaId,minValue,maxValue,companyIds, handleFetchCompanyFinancialDetails);
				}
			}



			function handleFetchCompanyFinancialDetails(data){
				try{
    	        	var disabledZone = $('disabledZone');
	            	disabledZone.style.display='none';
					if(data != null && data.length > 0){
						for(var i=0;i< data.length; i++){
							var found = false;
							for(var j=0;j < companiesFinancialData.length;j++){
								if(data[i].companyNumber == companiesFinancialData[j].companyNumber){
									// This company already exists in the list.
									found = true;
									companiesFinancialData[j].year1 = data[i].year1;	// update the latest data.
									break;
								}
							}
							if(!found){
								companiesFinancialData.push(data[i]);
							}
						}
					}
                    displayTable();
					//sorttable.init();
					markAllreadyPresentCompanies();
					calculateCompanies();
				}catch(e){
					alert("handleFetchCompanyFinancialDetails " + e);
				}
			}

			// Function to render the JST template table with the current data.
			function displayTable(){
				if(companiesFinancialData.length == 0){
					$("divTblFinancial").innerHTML = "";
					return;
				}
				var obj = new Object();
				obj.companies = companiesFinancialData;
				obj.financialSector = document.frmCustomiseReportTab.selFinancialCriteria.options[document.frmCustomiseReportTab.selFinancialCriteria.selectedIndex].text;
				var result = TrimPath.processDOMTemplate("tableTemplate", obj);
				$("divTblFinancial").innerHTML = result;
			}

			// Change the color of the companies in the table that are already present in the right-side list.
			function markAllreadyPresentCompanies(){
				try{
					if(companiesFinancialData == null || companiesFinancialData.length == 0)return;
					for(var i=0;i<document.frmCustomiseReportTab.chkFinancials.length;i++){
						var present = false;
						var companyId = document.frmCustomiseReportTab.chkFinancials[i].value;
						for(var t=0;t<document.frmCustomiseReportTab.selAddCompanyList.options.length;t++){
							if(companyId == document.frmCustomiseReportTab.selAddCompanyList.options[t].value){
								present = true;
								break;
							}
						}
						if(present){
							$("tblCompanyFinancialDetails").rows[i+1].style.color = '#000000';
						}else{
							$("tblCompanyFinancialDetails").rows[i+1].style.color = 'green';
						}
					}
				}catch(e){
					alert("markAllreadyPresentCompanies " + e);
				}
			}

			// Add the selected companies in the table to the list.
			function addCompaniesToList(){
				try{
					var companiesToMove = new Array();
					for(var i=0;i<document.frmCustomiseReportTab.chkFinancials.length;i++){
						if(document.frmCustomiseReportTab.chkFinancials[i].checked){
							// check if this company is already present in the selected list or not.
							var alreadySelected = false;
							for(var y=0;y<selectedCompanies.length;y++){
								if(document.frmCustomiseReportTab.chkFinancials[i].value == selectedCompanies[y].companyNumber){
									 alreadySelected = true;
									 break;
								}
							}
							if(!alreadySelected){
								var opt = new Option();
								opt.value = document.frmCustomiseReportTab.chkFinancials[i].value;
								opt.text = companiesFinancialData[i].companyName;
								document.frmCustomiseReportTab.selAddCompanyList.options.add(opt);
								companiesToMove.push(companiesFinancialData[i].companyNumber);	// push the index of the company in the main array.
							}
							document.frmCustomiseReportTab.chkFinancials[i].checked = false;
						}
					}
					moveCompanies(companiesToMove,companiesFinancialData,selectedCompanies);
                    displayTable();
					markAllreadyPresentCompanies();
					calculateCompanies();
				}catch(e){
					alert("addCompaniesToList :: " + e);
				}
			}

			// Remove a company from list 2 and add it back to list 1.
			function removeCompanyFromList(){
				var companiesToMove = new Array();
				var lstFrom = document.frmCustomiseReportTab.selAddCompanyList;
				for(var x = lstFrom.options.length - 1; x >=0;x--){
					if(lstFrom.options[x].selected){
						companiesToMove.push(lstFrom.options[x].value);
						lstFrom.remove(x);
					}
				}
				moveCompanies(companiesToMove,selectedCompanies,companiesFinancialData);
            	displayTable();
				markAllreadyPresentCompanies();
				calculateCompanies();
			}

			function  moveCompanies(companiesToMove,moveFrom,moveTo){
				if(companiesToMove.length == 0) return;
				var companyIds = companiesToMove.join();
				for(var i = moveFrom.length - 1; i >=0; i--){
					if(companyIds.indexOf(moveFrom[i].companyNumber) != -1){
						moveTo.push(moveFrom[i]);
						moveFrom.splice(i,1);
					}
				}
			}

			function moveList(){
				companiesFinancialData = new Array();
				for(var i=selectedCompanies.length-1;i>=0;i--){
					companiesFinancialData.push(selectedCompanies[i]);
					document.frmCustomiseReportTab.selAddCompanyList.remove(i);
				}
				selectedCompanies = new Array();
				displayTable();
				markAllreadyPresentCompanies();
				calculateCompanies();
			}

			function saveCustomReport(){
				if(selectedCompanies.length == 0){
					alert("There are no selected companies");
					return;
				}
				var companies = "";
				for(var i=0;i<selectedCompanies.length;i++){
					companies += "," + selectedCompanies[i].companyNumber;
				}
				companies = companies.substr(1);
				var reportName = prompt("Enter the report name","");
				reportName.trim();
				if(reportName == ""){
					alert("Invalid report name");
					return;
				}
				MsalResearchersManager.addCustomReport(reportName,customerDetailsId,companies,handleAddCustomReport);
			}

			function handleAddCustomReport(data){
				var sel =  $("selReportsTab4");
				var opt = new Option();
				opt.text = data.reportTitle;
				opt.value= data.reportTitlesId;
				sel.options.add(opt);
				alert("Custom report added");
			}

			///////////////////////////// code for range-selection of records ////////////////////
			var lastSelectedIndex = -1;

			function rangeSelect(elem,oEvent) {
				try{
					var currentIndex = elem.rowIndex - 1;
			        var isShiftDown = (oEvent.shiftKey == true);
			        var currentCkhBox = document.frmCustomiseReportTab.chkFinancials[currentIndex];

			        currentCkhBox.checked = ! currentCkhBox.checked; // since it was a click, update the chedked status.

			        var isCurrentChecked = currentCkhBox.checked;

					if(isShiftDown &&  (lastSelectedIndex != -1) && isCurrentChecked){
						// range select.
						var min = Math.min(lastSelectedIndex,currentIndex);
						var max = Math.max(lastSelectedIndex,currentIndex);

						for(var i=min;i<=max;i++){
							document.frmCustomiseReportTab.chkFinancials[i].checked  = true;
						}
					}else{
						if(isCurrentChecked){
							// a simple select. Save the code for the next (possible) range select.
							lastSelectedIndex = currentIndex;
						}else{
							// it was a uncheck - remove the range-select option.
							lastSelectedIndex = -1;
						}
					}

					// update the background colors of the table rows according to the selection
					// status of the checkboxes.
					var rows = $("tblCompanyFinancialDetails").rows;
					var chks = document.frmCustomiseReportTab.chkFinancials;

					for(var t=0;t<chks.length;t++){
						if(chks[t].checked){
							rows[t + 1].style.backgroundColor='#eeeeee';
						}else{
							rows[t + 1].style.backgroundColor='#ffffff';
						}
					}
				}catch(e){
					alert("rangeSelect " + e);
				}
			}


			function calculateCompanies(){
				$("divCompanyListLeft").innerHTML = companiesFinancialData.length + " Companies in the selected report";
				$("divCompanyListRight").innerHTML = selectedCompanies.length + " Companies selected";
			}

			/////////////////////////////end code for range-selection of the check boxes ////////////////////

		</script>

		<script>
            //////// Scripts for the SWF-based Tab 4 implementation.//////////////////

			// Scripts for the custom reports menus.
			function createMenubar(){
				MsalResearchersManager.getReportsList(handleReportNamesForMenubar);
			}
	
			function handleReportNamesForMenubar(data){
				customReports = new Array();
				if(data != null){
					for(var i=0;i<data.length;i++){
						if(data[i].customReport == true){
							customReports.push(data[i]);
						}
					}
				}
				jQuery("#staticMenuBar").html("");
				initjsDOMenu(customReports);
			}
			
			// Function to get the pointer to the SWF.
			function getMyApp(appName) {
			    if (navigator.appName.indexOf ("Microsoft") !=-1) {
			        return window[appName];
			    } else {
			        return document[appName];
			    }
			}

			function saveCustomReportSWF(reportName,companies,selectedForReport){
				MsalResearchersManager.addCustomReport(reportName,customerDetailsId,companies,selectedForReport,handleAddCustomReportSWF);
			}

			function handleAddCustomReportSWF(data){
				getMyApp("tab4").customReportSavedCallback(data);
				createMenubar();
			}

			function getReportNamesSWF(){
				MsalResearchersManager.getReportsList(handleGetReportNames);
			}

			function handleGetReportNames(data){
				//alert(data[0].reportTitle + " : " + data[0].customReport + " : " + data[0].noOfCompaniesInDatabase);
				//getMyApp("tab4").reportListToAdd(data);
				
				var reportChunkSize = <%=ApplicationResources.getInstance().getProperty("reportChunkSize")%>;
				
				if(data != null && data.length > 0){
					var reports = new Array();
					
					for(var i=0; i < data.length; i++){
						var noOfCompanies = parseInt(data[i].noOfCompaniesInDatabase); 

						if(noOfCompanies > reportChunkSize){
							// break the report into 'n' chunks
							var pages = Math.floor(noOfCompanies / reportChunkSize);
							if(noOfCompanies % reportChunkSize > 0)pages++;
							for(var p = 1;p <= pages;p++){
								reports.push({"reportTitlesId" : data[i].reportTitlesId , "reportTitle" : data[i].reportTitle + " - Part " + p, "page" : p});
							}
						}else{
							reports.push({"reportTitlesId" : data[i].reportTitlesId , "reportTitle" : data[i].reportTitle});
						}
					}
						
					getMyApp("tab4").reportListToAdd(reports);
				}
			}
			
			function deleteCustomReport(reportId, reportName){
				if(confirm('Do you really want to delete the report ' + reportName)){
					MsalResearchersManager.deleteCustomReport(reportId, handleDeleteCustomReport);
				}
			}

			function handleDeleteCustomReport(data){
				handleReportNamesForMenubar(data);
				try{
					if(getMyApp("tab4").reportListToAddForBIBService){
						handleGetReportNames(data);
					}
				}catch(e){
					//ignore
				}
			}
			
			function renameCustomReport(reportId, reportName){
				var newReportName = prompt("New Report Name", reportName);
				if(newReportName != null && newReportName.length > 0){
					/*if(newReportName.indexOf('\'') > -1 || newReportName.indexOf('\"') > -1 ){
						alert("Error : Illegal characters in the report name.")
						return;
					}*/
					// same result handling as in delete custom report.
					MsalResearchersManager.renameCustomReport(reportId, newReportName, handleDeleteCustomReport); 
				}
			}			
		</script>
		<%
			}
		%>
	    <link href="css/master.css" rel="stylesheet" type="text/css">

	</head>
	<body onload ="isSessionValid();" onunload="logOutOnUnload()">

		<jsp:include page = "mr_headerFreeUpdates.jsp"/>

		<!-- DIV for displaying the option of staying logged in 10 seconds before the actual logoff -->
		<div align="center" id="divStayLoggedIn" style="color:black;background-color:#7823CD;visibility:hidden;position:absolute;left:280px;top:350px">
			<%= request.getHeader("user-agent").indexOf("MSIE") != -1 ? "<BR>" : "" %>
			<h3 style="padding: 2px;font-family: Verdana, Helvetica, Arial, sans-serif;font-size: 15px;vertical-align:center;cursor:hand;" onclick="stayLoggedOn()">&nbsp; Click here to stay logged in to the Free Updates Service &nbsp;</h3>
		</div>

		<div align="center">
			<table width="750" align="center" cellpadding="0" cellspacing="0" border="0">
				<tr>
					<td>
						<br>
						<ul id="maintab" class="shadetabs">
							<li class="selected"><a href="#" rel="divDownloadReportsTab">&nbsp;&nbsp;&nbsp;Download Report&nbsp;&nbsp;&nbsp;</a></li>
							<li><a href="#" rel="divAddCompaniesTab" id="tabAddCompanies">&nbsp;&nbsp;&nbsp;Add Companies&nbsp;&nbsp;&nbsp;</a></li>
							<li><a href="#" rel="divDeleteCompaniesTab" id="tabDelCompanies">&nbsp;&nbsp;&nbsp;Delete Companies&nbsp;&nbsp;&nbsp;</a></li>
						<%
						if(showCustomReportsTab){
						%>
							<!--<li><a href="#" rel="divCustomiseReportTab" id="tabCustomiseReport">&nbsp;&nbsp;&nbsp;Customise Report&nbsp;&nbsp;&nbsp;</a></li>-->
							<li><a href="#" rel="divCustomiseReportTabSWF" id="tabCustomiseReportSWF">&nbsp;&nbsp;&nbsp;Customised Report&nbsp;&nbsp;&nbsp;</a></li>
						<%
						}
						%>
						</ul>

						<!-- tab 1 starts -->
						  	<%
						  		// retreive the data for the PDF downloads and download history tables.
								String reportIds = String.valueOf(bean.getReportTitlesId());
								if(bean.getAdditionalReportNumbers() != null){
									reportIds += bean.getAdditionalReportNumbers().replace('/',',');
								}

        						// get the report PDF status and download history.
        						PDFDownloadDetailsBean[] pdfBeans = IndustryWatchManager.getPDFDetailsForFreeUpdatesCustomer(reportIds, MerlinUtilities.REPORT_TYPE_PDF);
        						PDFDownloadDetailsBean[] xlsBeans = IndustryWatchManager.getPDFDetailsForFreeUpdatesCustomer(reportIds, MerlinUtilities.REPORT_TYPE_XLS);
        						PDFDownloadDetailsBean[] rankingBeans = IndustryWatchManager.getPDFDetailsForFreeUpdatesCustomer(reportIds, MerlinUtilities.REPORT_TYPE_RANKINGS);
        						
        						PDFDownloadDetailsBean[] pdfDownloadBeans = IndustryWatchManager.getDownloadHistoryForFreeUpdates(customerDetailsId);

								DbResultSet reportsForUser = (DbResultSet)session.getAttribute("reportsForUser");
								
								SimpleDateFormat fmt = new SimpleDateFormat("dd MMMMM yyyy");
						  	%>

						  <div id="divDownloadReportsTab" style="height:550px;MARGIN:0; BACKGROUND-COLOR: white;border-style:solid;border-width:1px;border-color:yellow;display:none">
						  	<p/>
						  	<div align="left"  style='margin-left:10px;'>
								<p>
						  		<ul id="downloadtab" class="innershadetabs">
									<li class="selected"><a href="#" rel="divReportsAvailable" style="font-size: 11px">eBook Report - (PDF)</a></li>
								<% if(showCustomReportsTab){ %>
									<li><a href="#" rel="divSpreadsheetReports" style="font-size: 11px">Report Data - (spreadsheet)</a></li>
									<li><a href="#" rel="divRankingsReports" style="font-size: 11px">Report Rankings - (spreadsheet)</a></li>
								<% } %>
									<li><a href="#" rel="divDownloadHistory" style="font-size: 11px">Download History</a></li>
						  		</ul>


								<div id="divReportsAvailable"  style="height:470px;width:730;MARGIN:0; BACKGROUND-COLOR: white;border-style:solid;border-width:1px;display:none">
									<br>
									<div align="right" style="font:11px verdana,arial, sans-serif ;">
										<input type='button' id="btnRefresh" value='Refresh' onclick="reloadPage()" style ="FONT-SIZE: 11px; WIDTH: 100px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
									</div>
									<br>
							  		<div style="overflow:auto;height:400;width:730;border:none;">
									<table width='100%' cellspacing='0' cellpadding = '5' style="border-style: solid;border-width: 1px;font:11px verdana,arial, sans-serif ;">
											<tr>
												<th style="width:370">Report Title</th>
												<th style="width:80;text-align:right">Size</th>
												<th style="width:140;text-align:right">Edition</th>
												<th style="width:110;text-align:right">Status</th>
											</tr>
											<%
												for(int i=0;i<pdfBeans.length;i++){

													int status = pdfBeans[i].getStatus();
													String message = "";
													boolean clickable = false;
													String rowColor = null;
													String cursor = "default";

													switch(status){
														case MerlinUtilities.REPORT_STATUS_IN_PROGRESS:
															message = "Preparing Edition";
															rowColor = "black";
															break;
														case MerlinUtilities.REPORT_STATUS_AVAILABLE:
															clickable = true;
															message = "Click to download";
															rowColor = "#038243";
															cursor = "pointer";
															break;
													}

													out.print("<tr style='color:" + rowColor + ";cursor:" + cursor + "'" + (clickable?"onclick='downloadReport(\"" + pdfBeans[i].getReportId() + "\",this," + MerlinUtilities.REPORT_TYPE_PDF + ")'":"") + ">");
													out.print("<td>" + pdfBeans[i].getReportTitle() + "</td>");
													out.print("<td style='text-align: right'>" + MerlinUtilities.formatFileSize(pdfBeans[i].getReportSize()) + "</td>");
													out.print("<td style='text-align: right'>" + pdfBeans[i].getReportEdition() + "</td>");
													out.print("<td style='text-align: right'>" + message + "</td>");
													out.println("</tr>");

												}
											%>
									</table>
									</div>
								</div>

								<div id="divSpreadsheetReports"  style="height:470px;width:730;MARGIN:0; BACKGROUND-COLOR: white;border-style:solid;border-width:1px;display:none">
									<br>
									<div align="right" style="font:11px verdana,arial, sans-serif ;">
										<input type='button' id="btnRefresh" value='Refresh' onclick="reloadPage()" style ="FONT-SIZE: 11px; WIDTH: 100px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
									</div>
									<br>
							  		<div style="overflow:auto;height:400;width:730;border:none;">
									<table width='100%' cellspacing='0' cellpadding = '5' style="border-style: solid;border-width: 1px;font:11px verdana,arial, sans-serif ;">
											<tr>
												<th style="width:370">Report Title</th>
												<th style="width:80;text-align:right">Size</th>
												<th style="width:140;text-align:right">Edition</th>
												<th style="width:110;text-align:right">Status</th>
											</tr>
											<%
												for(int i=0;i<xlsBeans.length;i++){

													int status = xlsBeans[i].getStatus();
													String message = "";
													boolean clickable = false;
													String rowColor = null;
													String cursor = "default";

													switch(status){
														case MerlinUtilities.REPORT_STATUS_IN_PROGRESS:
															message = "Preparing Edition";
															rowColor = "black";
															break;
														case MerlinUtilities.REPORT_STATUS_AVAILABLE:
															clickable = true;
															message = "Click to download";
															rowColor = "#038243";
															cursor = "pointer";
															break;
													}

													out.print("<tr style='color:" + rowColor + ";cursor:" + cursor + "'" + (clickable?"onclick='downloadReport(\"" + xlsBeans[i].getReportId() + "\",this," + MerlinUtilities.REPORT_TYPE_XLS + ")'":"") + ">");
													out.print("<td>" + xlsBeans[i].getReportTitle() + "</td>");
													out.print("<td style='text-align: right'>" + MerlinUtilities.formatFileSize(xlsBeans[i].getReportSize()) + "</td>");
													out.print("<td style='text-align: right'>" + xlsBeans[i].getReportEdition() + "</td>");
													out.print("<td style='text-align: right'>" + message + "</td>");
													out.println("</tr>");

												}
											%>
									</table>
									</div>
								</div>

								<div id="divRankingsReports"  style="height:470px;width:730;MARGIN:0; BACKGROUND-COLOR: white;border-style:solid;border-width:1px;display:none">
									<br>
									<div align="right" style="font:11px verdana,arial, sans-serif ;">
										<input type='button' id="btnRefresh" value='Refresh' onclick="reloadPage()" style ="FONT-SIZE: 11px; WIDTH: 100px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
									</div>
									<br>
							  		<div style="overflow:auto;height:400;width:730;border:none;">
									<table width='100%' cellspacing='0' cellpadding = '5' style="border-style: solid;border-width: 1px;font:11px verdana,arial, sans-serif ;">
											<tr>
												<th style="width:370">Report Title</th>
												<th style="width:80;text-align:right">Size</th>
												<th style="width:140;text-align:right">Edition</th>
												<th style="width:110;text-align:right">Status</th>
											</tr>
											<%
												for(int i=0;i<rankingBeans.length;i++){

													int status = rankingBeans[i].getStatus();
													String message = "";
													boolean clickable = false;
													String rowColor = null;
													String cursor = "default";

													switch(status){
														case MerlinUtilities.REPORT_STATUS_IN_PROGRESS:
															message = "Preparing Edition";
															rowColor = "black";
															break;
														case MerlinUtilities.REPORT_STATUS_AVAILABLE:
															clickable = true;
															message = "Click to download";
															rowColor = "#038243";
															cursor = "pointer";
															break;
													}

													out.print("<tr style='color:" + rowColor + ";cursor:" + cursor + "'" + (clickable?"onclick='downloadReport(\"" + rankingBeans[i].getReportId() + "\",this," + MerlinUtilities.REPORT_TYPE_RANKINGS + ")'":"") + ">");
													out.print("<td>" + rankingBeans[i].getReportTitle() + "</td>");
													out.print("<td style='text-align: right'>" + MerlinUtilities.formatFileSize(rankingBeans[i].getReportSize()) + "</td>");
													out.print("<td style='text-align: right'>" + rankingBeans[i].getReportEdition() + "</td>");
													out.print("<td style='text-align: right'>" + message + "</td>");
													out.println("</tr>");

												}
											%>
									</table>
									</div>
								</div>

								<div id="divDownloadHistory"  style="height:420px;width:730;MARGIN:0; BACKGROUND-COLOR: white;border-style:solid;border-width:1px;display:none">
								<%
									if(pdfDownloadBeans != null && pdfDownloadBeans.length > 0){
								%>
									<p>
									<div style='height:380;overflow:auto;width:730;'>
										<table cellspacing='0' cellpadding = '5' style="width:710;border-style: solid;border-width: 1px;font:11px verdana,arial, sans-serif ;">
										<thead>
											<tr>
												<th style="width:370">Report Title</th>
												<th  style='width:110;text-align: right'>Downloaded On</th>
											</tr>
										</thead>
										<tbody valign='top'>
										<%
											for(int i=0;i<pdfDownloadBeans.length;i++){
										%>
											<tr>
												<td><%=pdfDownloadBeans[i].getReportTitle()%></td>
												<td  style='text-align: right'><%=fmt.format(pdfDownloadBeans[i].getDownloadDate())%></td>
											</tr>
										<%
											}
										%>
										</table>
									</div>
								<%
									}
								%>
								</div>
							</div>
							<p/>
						  </div>
						<!-- tab 1 ends -->

						<!-- tab 2 starts -->
						<div id="divAddCompaniesTab" style="MARGIN:0; BACKGROUND-COLOR: white;border-style:solid;border-width:1px;border-color:yellow;display:none">
							<br>
							<DIV ALIGN="CENTER" ID="divMessage">&nbsp;</DIV>
							<br>
							<FORM name="frmSearch" method="post" target="_top" action="merlin" onsubmit="searchCompanyByKeyword(this.txtSearch.value,this);return false;">

								 <input type="hidden" name="hidCompanies">
								 <input type="hidden" name="hidCompaniesToRemove">
								 <input type="hidden" name="mode">
										<div style="PADDING-RIGHT: 0px; PADDING-LEFT: 0px; PADDING-BOTTOM: 0px; PADDING-TOP: 0px">
											<table style="MARGIN: 0px 0px 0px 9px; WIDTH: 720px" cellpadding="1" cellspacing="0">
										  		<%
										  			if(reportsForUser.size() > 1){
										  		%>
													<tr>
														<td colspan="3" style="FONT: 11px arial, verdana, sans-serif;">
												  			Select the report you want to use :
															<select id="selReportsTab2" style="FONT: 11px arial, verdana, sans-serif;" onchange="reportChanged(this)">
													  		<%
													  			for(int i=0;i<reportsForUser.size();i++){
													  				ReportTitlesBean rtBean = (ReportTitlesBean)reportsForUser.get(i);
													  				if(!rtBean.isCustomReport()){
														  				out.println("<option value='" + rtBean.getReportTitlesId() + "'" + (rtBean.getReportTitlesId() == reportId ? "selected":"") + ">" + rtBean.getReportTitle() + "</option>");
														  			}
													  			}
													  		%>
												  			</select>
												  			<br>
														</td>
													</tr>
										  		<%
										  			}
										  		%>
												<tr>
													<td style="FONT: 11px arial, verdana, sans-serif; WIDTH: 33%">
														<b>Search for <input type="radio" name="radSearchType" value="alphakey" checked>Alphakey or <input type="radio" name="radSearchType" value="keyword"> Keyword (Name, Keyword, Director, Registration Number or Address).</b>
													</td>
												</tr>
												<tr>
													<td>
														<input name="txtSearch" style="TEXT-TRANSFORM: uppercase; WIDTH: 350px;FONT: 11px arial, verdana, sans-serif;"  >
														<input name="btnSearch" type="submit" style="FONT-SIZE: 11px; WIDTH: 95px" value="Search For Firm  >" >
													&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="button"  name="btnPrintPDF" style="FONT-SIZE: 11px; WIDTH: 95px" value="Print PDF" onclick="generatePDF(this.form.lstCompanies.value)">
													</td>
												</tr>
											</table>
										</div>
										<div style="PADDING-RIGHT: 0px; PADDING-LEFT: 0px; PADDING-BOTTOM: 7px; PADDING-TOP: 5px">
											<table style="MARGIN: 0px 0px 0px 9px; WIDTH: 710px" cellpadding="1" cellspacing="0">
												<tr>
													<td style="WIDTH: 260px">
														<span style="FONT: 11px arial, verdana, sans-serif">The following companies were found by this search<br >(click to view a company of interest)</span>
														<SELECT name="lstCompanies" size="4" MULTIPLE style="WIDTH: 250px; FONT: 11px arial, verdana, sans-serif;" onchange="searchCompanyByCompanyNumber(this.value,this.form)">
														</SELECT>
													</td>
													<td style="TEXT-ALIGN: center">
														<input type="button" name="btnAddCompany" value="Add Company  >"  style ="FONT-SIZE: 11px; WIDTH: 130px" onclick="addCompany()">
														<input type="button" name="btnRemoveCompany" value="   < Remove Company" style="FONT-SIZE: 11px; WIDTH: 130px" onclick="deleteCompany(this.form.lstSelectedCompanies)">
														<input type="button" name="btnUpdate" value="Send FREE Update" style="FONT-SIZE: 11px; WIDTH: 130px" onclick="sendReportData(this.form)">
													</td>
													<td style="WIDTH: 260px; TEXT-ALIGN: right">
														<span id="spnSelectedCompanies" style="FONT: 11px arial, verdana, sans-serif">Companies to include in your new report<br>(click to delete a company)</span>
														<SELECT name="lstSelectedCompanies" size="4" MULTIPLE style="WIDTH: 250px; FONT: 11px arial, verdana, sans-serif;">
														<%

											   				// fetch the previously selected companies from the database.
											   				String strCompanies = null;
											   				ArrayList list = MsalResearchersManager.getSelectedCompanies(bean.getEmailAddress(),bean.getReportTitlesId());
											   				if(list != null && list.size() > 0){
											   					StringBuffer sBufComps = new StringBuffer();
																int length = list.size();
																for(int i=0;i<length - 1;i++){
																	String arr[] = (String[])list.get(i);
																	sBufComps.append(arr[0]).append(separatorString).append(arr[1]).append(separatorString);
																}
																String arr[] = (String[])list.get(length - 1);
																sBufComps.append(arr[0]).append(separatorString).append(arr[1]);
												   				strCompanies = sBufComps.toString();
												   			}

															if(strCompanies != null && strCompanies.length() > 0){
																String arrCompanies[] = strCompanies.split(separatorPattern);
				                                           		for(int i=0;i< arrCompanies.length-1;i+=2){
															  		out.println("<option value=\'" + arrCompanies[i] + "\'>" + arrCompanies[i+1] + "</option>");
															  	}
															}
														%>
														</SELECT>
													</td>
												</tr>
											</table>
										</div>
										<div style="PADDING-RIGHT: 0px; PADDING-LEFT: 0px; PADDING-BOTTOM: 8px; PADDING-TOP: 3px" >
											<table style="MARGIN: 0px 0px 0px 9px; WIDTH: 710px" cellpadding="0" cellspacing="0">
												<tr>
													<td style="FONT: 11px arial, verdana, sans-serif; WIDTH: 250px"><strong>Address</strong></td>
													<td style="FONT: 11px arial, verdana, sans-serif; WIDTH: 33%"><strong>Shareholders</strong></td>
												</tr>
												<tr>
													<td>
														<DIV id="divAddress" style="MARGIN: 0px 10px 0px 0px;BORDER: 1px solid;overflow:auto; HEIGHT:70px; WIDTH: 240px; FONT: 11px arial, verdana, sans-serif;"></DIV>
													</td>
													<td>
														<DIV id="divShareholders" style="MARGIN: 0px 10px 0px 0px;BORDER: 1px solid;overflow:auto;HEIGHT:70px; WIDTH: 458px; FONT: 11px arial, verdana, sans-serif;" ></DIV>
													</td>
												</tr>
												<tr>
													<td style="FONT: 11px arial, verdana, sans-serif; WIDTH: 33%"><strong>Directors &amp; Company Secretary</strong></td>
													<td style="FONT: 11px arial, verdana, sans-serif; WIDTH: 33%"><strong>Ultimate Parent(UP), Parent(P), Subsidiaries Undertakings(S)</strong></td>
												</tr>
												<tr>
													<td>
														<SELECT name="lstDirectors" style="MARGIN: 0px 10px 0px 0px;HEIGHT:72px; WIDTH: 240px;FONT: 11px arial, verdana, sans-serif;" MULTIPLE onchange="searchCompanyByDirector(this.value,this.form)"></SELECT>
													</td>
													<td>
														<DIV id="divSubsidiary" style="MARGIN: 0px 10px 0px 0px;BORDER: 1px solid;overflow:auto;HEIGHT:70px; WIDTH: 458px;FONT: 11px arial, verdana, sans-serif;" ></DIV>
													</td>
												</tr>
												<tr>
													<td  style="FONT: 11px arial, verdana, sans-serif; WIDTH: 33%" colspan="2"><strong>Business Description</strong></td>
												</tr>
												<tr>
													<td colspan="2"><DIV style="BORDER: 1px solid;overflow:auto;MARGIN: 0px; WIDTH: 708px; HEIGHT:60px; FONT: 11px arial, verdana, sans-serif;" id="divBusinessDescription"></DIV>
													</td>
												</tr>
												<tr>
													<td  style="FONT: 11px arial, verdana, sans-serif; WIDTH: 33%" colspan="2"><strong>Summary Financials</strong>
													</td>
												</tr>
												<tr>
													<td colspan="2">
														<DIV id="divSummaryFinancial" style="BORDER: 1px solid;overflow:auto;MARGIN: 0px; WIDTH: 708px; HEIGHT:220px; FONT: 11px arial, verdana, sans-serif;"></DIV>
													</td>
												</tr>
											</table>
										</div>
									</FORM>
						  </div>
						<!-- tab 2 ends -->
						<!-- tab 3 starts -->
						<div id="divDeleteCompaniesTab" style="MARGIN:0; BACKGROUND-COLOR: white;border-style:solid;border-width:1px;border-color:yellow;display:none">
							<form name="frmDeleteCompaniesTab">
						  	<p>
								<div>
									<TABLE id=TABLE1 cellSpacing=1 cellPadding=1 width="100%" border=0 style='margin-left:15px'>
							  		<%
							  			if(reportsForUser.size() > 1){
							  		%>
										<tr>
											<td colspan="3" style="FONT: 11px arial, verdana, sans-serif;">
									  			Select the report you want to use :
												<select id="selReportsTab3" style="FONT: 11px arial, verdana, sans-serif;" onchange="reportChanged(this)">
										  		<%
										  			for(int i=0;i<reportsForUser.size();i++){
										  				ReportTitlesBean rtBean = (ReportTitlesBean)reportsForUser.get(i);
										  				if(!rtBean.isCustomReport()){
										  					out.println("<option value='" + rtBean.getReportTitlesId() + "'" + (rtBean.getReportTitlesId() == reportId ? "selected":"") + ">" + rtBean.getReportTitle() + "</option>");
										  				}
										  			}
										  		%>
									  			</select>
											</td>
										</tr>
							  		<%
							  			}
							  		%>
										<TR>
											<TD width="40%" >
													<div style="FONT: 11px arial, verdana, sans-serif;height:10px;">Companies to be removed</div><P>
													<SELECT name="selDelCompanyList" style="WIDTH: 271px; HEIGHT: 316px;FONT: 11px arial, verdana, sans-serif;color:red" size="2" ondblclick="addCompanyTab3()" multiple>
													</SELECT>
											</TD>
											<td style='vertical-align:middle'>
												<input type="button" name="btnLoadCompanies" value="Get Report List" style ="FONT-SIZE: 11px; WIDTH: 130px" onclick="loadCompaniesInReport()">
												<br>&nbsp;<p>
												<input type="button" name="btnAddCompany" value="Add Company  >"  style ="FONT-SIZE: 11px; WIDTH: 130px" onclick="addCompanyTab3()" >
												<input type="button" name="btnRemoveCompany" value="   < Remove Company" style="FONT-SIZE: 11px; WIDTH: 130px" onclick="removeCompanyTab3()">
												<input type="button" name="btnUpdate" value="Send Free Update" style="FONT-SIZE: 11px; WIDTH: 130px"  onclick="sendReportData(document.frmSearch)">
											</td>
											<TD width="40%">
													<div id="divAddedCompanies" style="FONT: 11px arial, verdana, sans-serif;height:10px;">Companies now listed in the report</div><p>
													<SELECT name="selAddCompanyList" style="WIDTH: 271px; HEIGHT: 316px;FONT: 11px arial, verdana, sans-serif;" size="2" ondblclick="removeCompanyTab3()" multiple>
													</SELECT>
											</TD>
										</TR>
									</TABLE>
								</div>
							</P>
							</form>
						</div>
						<!-- tab 3 ends -->
						<%
						if(showCustomReportsTab){
						%>
						<!-- tab 4 starts -->
						<div id="divCustomiseReportTab" style="MARGIN:0; BACKGROUND-COLOR: white;border-style:solid;border-width:1px;border-color:yellow;display:none">
							<form name="frmCustomiseReportTab">
							  	<p>
									<div>
										<TABLE id=TABLE1 cellSpacing=1 cellPadding=1 width="100%" border=0 style='margin-left:15px'>
											<tr>
												<td colspan="3" style="FONT: 11px arial, verdana, sans-serif;">
										  			Select the report you want to use :
													<select name="selReportsTab4" id="selReportsTab4" style="FONT: 11px arial, verdana, sans-serif;" onchange="companyChanged = true">
											  		<%
											  			for(int i=0;i<reportsForUser.size();i++){
											  				ReportTitlesBean rtBean = (ReportTitlesBean)reportsForUser.get(i);
											  				out.println("<option value='" + rtBean.getReportTitlesId() + "'" + (rtBean.getReportTitlesId() == reportId ? "selected":"") + ">" + rtBean.getReportTitle() + "</option>");
											  			}
											  		%>
										  			</select>
												</td>
											</tr>

											<TR>
												<TD width="60%" style='vertical-align:top'>
														<div style="FONT: 11px arial, verdana, sans-serif;height:10px;" id="divCompanyListLeft">Companies in the selected report</div>
														<div id="divTblFinancial" style="overflow:auto;HEIGHT: 316px;FONT: 11px arial, verdana, sans-serif;">
														</div>
												</TD>
												<td style='vertical-align:middle'>
													<select name="selFinancialCriteria" size="1" style ="FONT-SIZE: 11px; WIDTH: 130px" onchange="fetchCompanyFinancialDetails(this.form,'select')">
														<option value="0">Select Data Here</option>
														<option value="1">County</option>
														<option value="2">Number of Employees</option>
														<option value="3">Total Tangible Assets</option>
														<option value="4">Total Fixed Assets</option>
														<option value="5">Total Current Assets</option>
														<option value="6">Total Current Liabilities</option>
														<option value="7">Working Capital</option>
														<option value="8">Net Assets</option>
														<option value="9">Long Term Loans</option>
														<option value="10">Other Long Term Liabilities</option>
														<option value="11">Shareholder Funds</option>
														<option value="12">Turnover</option>
														<option value="13">Gross Profit</option>
														<option value="14">Operating Profit</option>
														<option value="15">Profit Before Interest & Tax</option>
														<option value="16">Pre-tax Profit</option>
														<option value="17">Profit After Tax</option>
														<option value="18">Retained Profit</option>
													</select>
													<span style ="FONT-SIZE: 10px; WIDTH: 130px">
													Maximum&nbsp;<input type="text" style="width:50px" name="txtMaxValue"><br>
													Minimum&nbsp;&nbsp;<input type="text" style="width:50px" name="txtMinValue"><br>
													</span>
													<input type="button" name="btnLoadCompaniesTab4" value="Select" style ="FONT-SIZE: 11px; WIDTH: 130px" onclick="fetchCompanyFinancialDetails(this.form,'button')">
													<br>&nbsp;<p>
													<input type="button" name="btnAddCompanyTab4" value="Add Company  >"  style ="FONT-SIZE: 11px; WIDTH: 130px" onclick="addCompaniesToList()" >
													<input type="button" name="btnRemoveCompanyTab4" value="   < Remove Company" style="FONT-SIZE: 11px; WIDTH: 130px" onclick="removeCompanyFromList()">
													<input type="button" name="btnMoveList" value="<< Move List" style="FONT-SIZE: 11px; WIDTH: 130px"  onclick="moveList()">
													<input type="button" name="btnPrint" value="Print" style="FONT-SIZE: 11px; WIDTH: 130px"  onclick="saveCustomReport()">
												</td>
												<TD width="20%">
														<div style="FONT: 11px arial, verdana, sans-serif;height:10px;" id="divCompanyListRight">Companies selected</div><p>
														<SELECT name="selAddCompanyList" style="WIDTH:90%; HEIGHT: 316px;FONT: 11px arial, verdana, sans-serif;" size="2" ondblclick="removeCompanyTab3()" multiple>
														</SELECT>
												</TD>
											</TR>
										</TABLE>
									</div>
								</P>
							</form>

						</div>
						<!-- tab 4 ends -->

						<div id="divCustomiseReportTabSWF" style="MARGIN:0; BACKGROUND-COLOR: white;border-style:solid;border-width:1px;border-color:yellow;display:none">
						  	<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"
									id="tab4" width="750" height="420"
									codebase="http://fpdownload.macromedia.com/get/flashplayer/current/swflash.cab">
									<param name="movie" value="tab4.swf" />
									<param name="quality" value="high" />
									<param name="bgcolor" value="#ffffff" />
									<param name="WMODE" value="opaque"/>
									<param name="allowScriptAccess" value="sameDomain" />
									<param name="flashVars" value="reportId=<%=reportId%>">
									<embed src="tab4.swf" quality="high" bgcolor="#ffffff"
										width="750" height="420" name="tab4" align="middle"
										play="true"
										loop="false"
										quality="high"
										WMODE="opaque"
										allowScriptAccess="sameDomain"
										type="application/x-shockwave-flash"
										flashVars="reportId=<%=reportId%>"
										pluginspage="http://www.adobe.com/go/getflashplayer">
									</embed>
							</object>
						</div>
						<%
						}
						%>
	  				</td>
				</tr>
				<tr>
					<td><jsp:include page="mr_footer.jsp"/></td>
				</tr>
			</table>
		</div>
		<script type="text/javascript">
			//Start Tab Content script for UL with id="maintab" Separate multiple ids each with a comma.
			initializetabcontent("maintab","downloadtab");
			//load the menu. If the custom reports tab is available, run the 
			// full createMenubar() function, else run the simpler one.
			if(jsShowCustomReportsTab){
				createMenubar();
			}else{
				initjsDOMenu(null);	
			}
			
		</script>
		<%
		if(showCustomReportsTab){
		%>
		<!-- textarea containing the JST template for rendering the table structure -->
		<textarea id="tableTemplate" style="display:none">
			<table class="sortable" id="tblCompanyFinancialDetails" width="100%" height="100%" align="center" border="0" cellspacing="0" cellpadding="1" style="border : none">
				<thead  style="border :none">
					<tr style='background-color:yellow;color:black;'id="gridHeader">
						<th width="70%" class="sortablecolumn" style="text-align:center;border :none; vertical-align:bottom;font-size:11px">Company Name</th>
						<th width="30%" class="sortablecolumn" style="text-align:right;border :none; vertical-align:bottom;font-size:11px">Sort</th>
					</tr>
				</thead>
				<tbody id="gridData"  style="border :none;">
					{for company in companies}
						<tr onclick="rangeSelect(this,event)" checked="false">
							<td style="text-align:left;border :none;vertical-align:middle;FONT: 11px arial, verdana, sans-serif;">${company.companyName}<input type="checkbox" name="chkFinancials" style="display:none" value="${company.companyNumber}"></td>
							<td style="text-align:right;border :none;vertical-align:middle;FONT: 11px arial, verdana, sans-serif;">${company.year1}</td>
						</tr>
					{/for}
				</tbody>
			</table>
		</textarea>
    	<%
    	}
    	%>
	</body>
</html>